<?php

namespace app\controller;

use app\BaseController;
use app\common\Snowflake;
use app\model\LoginBackgroundModel;
use think\facade\Db;
use think\facade\Request;
use think\response\Json;
use think\exception\ValidateException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Background extends BaseController
{
    public function create(): Json
    {
        $data = Request::post();
        try {
            $this->validate($data, [
                'image_url' => 'require',
            ]);

            $snowflake = new Snowflake(1, 1);
            $data['background_id'] = $snowflake->nextId();
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['update_time'] = date('Y-m-d H:i:s');
            $result = LoginBackgroundModel::create($data);
            if ($result) {
                return json(['code' => 0, 'msg' => '新增成功', 'data' => $result]);
            } else {
                return json(['code' => 1, 'msg' => '新增失败', 'data' => []]);
            }
        } catch (ValidateException $e) {
            return json(['code' => 1, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }

    public function update($id)
    {
        $data = Request::post();
        try {
            $this->validate($data, [
                'image_url' => 'require',
            ]);
            $data['update_time'] = date('Y-m-d H:i:s');
            $result = LoginBackgroundModel::where('id', $id)->update($data);
            if ($result) {
                return json(['code' => 0, 'msg' => '编辑成功', 'data' => []]);
            } else {
                return json(['code' => 1, 'msg' => '编辑失败', 'data' => []]);
            }
        } catch (ValidateException $e) {
            return json(['code' => 1, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }

    public function delete($id)
    {
        // 1. 强制转换ID为正整数
        $id = filter_var($id, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
        if ($id === false) {
            return json(['code' => 400, 'msg' => 'ID必须为正整数']);
        }

        // 2. 查询记录（确认存在）
        $record = Db::name('login_backgrounds')
            ->field('id, background_id') 
            ->fetchSql()
            ->where('id', $id)
            ->find();

        if (empty($record)) {
            return json([
                'code' => 404,
                'msg' => '记录不存在（ID:' . $id . '）',
                'debug' => ['sql' => Db::getLastSql()]
            ]);
        }

        // 3. 执行删除（核心逻辑）
        try {
            $affected = Db::name('login_backgrounds')
                ->where('id', $id)
                ->delete(); // 直接物理删除（无软删除）
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '服务器错误：' . $e->getMessage(),
                'debug' => ['error_code' => $e->getCode()]
            ]);
        }

        // 4. 返回结果
        return $affected > 0
            ? json(['code' => 0, 'msg' => '删除成功'])
            : json(['code' => 422, 'msg' => '删除失败（记录可能已删除）']);
    }

    public function list()
    {
        $backgroundId = Request::get('background_id');
        $isDisplay = Request::get('is_display');
        $page = Request::get('page', 1);
        $limit = Request::get('limit', 10);
        $query = LoginBackgroundModel::where(true);
        if ($backgroundId) {
            $query->where('background_id', $backgroundId);
        }
        if ($isDisplay!== null) {
            $query->where('is_display', $isDisplay);
        }
        $list = $query->order('id', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page,
            ]);
        $list->each(function ($item) {
            $item->is_display = $item->is_display? '是' : '否';
        });
        return json(['code' => 0, 'msg' => '获取列表成功', 'data' => $list]);
    }

    public function export()
    {
        $backgroundId = Request::get('background_id');
        $isDisplay = Request::get('is_display');
        $query = LoginBackgroundModel::where(true);
        if ($backgroundId) {
            $query->where('background_id', $backgroundId);
        }
        if ($isDisplay !== null) {
            $query->where('is_display', $isDisplay);
        }
        $list = $query->select();
        $list->each(function ($item) {
            $item->is_display = $item->is_display ? '是' : '否';
        });
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', '背景图ID');
        $sheet->setCellValue('B1', '图片URL地址');
        $sheet->setCellValue('C1', '是否展示');
        $sheet->setCellValue('D1', '修改时间');
        foreach ($list as $key => $item) {
            $row = $key + 2;
            $sheet->setCellValue('A' . $row, $item->background_id);
            $sheet->setCellValue('B' . $row, $item->image_url);
            $sheet->setCellValue('C' . $row, $item->is_display);
            $sheet->setCellValue('D' . $row, $item->update_time);
        }
        $date = date('Ymd');
        $fileName = $date . '_导出的登录背景图';
        $format = Request::get('format', 'csv');
        if ($format === 'csv') {
            $writer = new Csv($spreadsheet);
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
            header('Cache-Control: max-age=0');
        } elseif ($format === 'xls') {
            $writer = new Xlsx($spreadsheet);
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx"');
            header('Cache-Control: max-age=0');
        }
        $writer->save('php://output');
    }

}